import React, { useEffect, useMemo, useRef, useState } from 'react';
import Tabs from './Tabs';
import { Modal, RadioChangeEvent } from 'antd';
import './styles/send_command.less';
import SelectContent from './SelectContent';
import SendLink from './SendLink';
import SendVideo from './SendVideo';
import { useBusiness } from '../Context/BusinessContext';
import { IBusinessName } from '../Context/BusinessContext';
import SendForm, { IFormOption } from './SendForm';
import ZcoForm from '../ZcoForm';
import { Divider, Form } from 'antd';
import useSyncState from '../hooks/useSyncState';
import SendPDF from './SendPDF';
// import SendCardCollection from './SendCardCollection';
import CollectVariable from './CollectVariable';
import Transcript from './Transcript';
import styled from '@emotion/styled';
import AgentService from '@/modules/Agent';
import type { CheckboxValueType } from 'antd/es/checkbox/Group';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import VideoCollection from './VideoCollection';
import { useTranslation } from 'react-i18next';
import FormPreview from './FormPreview';

interface SendCommandProps {
	visible?: boolean;
	sendCommandModalType?: IBusinessName | null;
	showCustomerRoleOrName?: boolean;
	onOk?: () => void;
	onClose?: () => void;
}

interface customerNameProps {
	name: string | null;
	active: boolean;
	clientId: string;
	id: string;
}

interface customerRoleProps {
	name: string | null;
	active: boolean;
}
interface IPDFResource {
	name: string;
	url: string;
	size: number;
	suffix: string;
}

const initialPdfResource = {
	name: '',
	url: '',
	size: 0,
	suffix: ''
};

const hasDivider = [
	IBusinessName.FILL_FORM,
	IBusinessName.SEND_LINK,
	IBusinessName.SEND_CARD_COLLECTION,
	IBusinessName.SEND_VIDEO_LINK,
	IBusinessName.SEND_PDF,
	IBusinessName.SEND_VARIABLE_COLLECTION,
	IBusinessName.TRANSCRIPT_OF_TESTIMONY,
	IBusinessName.SHARED_PDF,
	IBusinessName.SEND_VIDEO_COLLECTION
];

enum UploadStatus {
	IDLE = 'IDLE',
	DONE = 'DONE',
	FAILED = 'FAILED',
	SUCCESS = 'SUCCESS',
	PROGRESS = 'PROGRESS'
}

const index = (props: SendCommandProps) => {
	const { t } = useTranslation();
	const { visible = false, sendCommandModalType, onOk, onClose, showCustomerRoleOrName } = props;

	const [tabTypes, setTabTypes] = useState<string>('customerNameTabs');

	const [title, setTitle] = useState<string>('');

	const { sendBusiness, startWhiteBoard, startPdfWhiteBoard } = useBusiness();

	const [customerName, setCustomerName] = useState<customerNameProps[]>([]);

	const [customerRole, setCustomerRole] = useState<customerRoleProps[]>([]);

	const [link, setLink] = useState<string>('');

	const [video, setVideo] = useState<string>('');

	const [errorMessage, setErrorMessage] = useState<string>('');

	const [selectErrorMessage, setSelectErrorMessage] = useState<string>('');

	const [selectErrorMessageRole, setSelectErrorMessageRole] = useState<string>('');

	const [formTemp, setFormTemp] = useSyncState<IFormOption[] | undefined>(undefined);

	const [pdfResource, setPdfResource] = useSyncState<IPDFResource>(initialPdfResource);

	const [pdfStatus, setPdfStatus] = useSyncState<UploadStatus>(UploadStatus.IDLE);

	const form = useRef<any>(null);

	const [cardType, setCardType] = useState<string>('');

	const [transcriptValue, setTranscriptValue] = useSyncState('');

	const defaultCheckedList: CheckboxValueType[] = [];
	const [checkedVariablesList, setCheckedVariablesList] = useSyncState<CheckboxValueType[]>(defaultCheckedList);
	const [checkVariablesListAll, setCheckVariablesListAll] = useSyncState(false);

	const [modalWidth, setModalWidth] = useSyncState<number>(520);

	const [videoCollectionTime, setVideoCollectionTime] = useSyncState<any>('');

	useEffect(() => {
		if (visible) {
			getTitle();
			getCustomerData();
		} else {
			setFormTemp(undefined);
			setCardType(''); // 重置卡证选择状态
			setCheckVariablesListAll(false);
			setCheckedVariablesList(defaultCheckedList);
			setPdfResource(initialPdfResource);
			setVideo('');
			setPdfStatus(UploadStatus.IDLE);
			setTabTypes('customerNameTabs');
			if (AgentService.transcriptData.length !== 0) {
				setTranscriptValue(AgentService.transcriptData[0].id);
			} else {
				setTranscriptValue('');
			}
		}
		console.log(showCustomerRoleOrName, 'showCustomerRoleOrName');
	}, [visible]);

	useEffect(() => {
		if (AgentService.transcriptData.length !== 0) {
			setTranscriptValue(AgentService.transcriptData[0].id);
		}
	}, [AgentService.transcriptData]);

	const getTitle = async () => {
		switch (sendCommandModalType) {
			case IBusinessName.SCREEN_SHOT:
				setTitle(t('select-client-for-screenshot') as string);
				break;
			case IBusinessName.SCREEN_SHARE:
				setTitle(t('select-client-for-screen-share') as string);
				break;
			case IBusinessName.SEND_LINK:
				setTitle(t('tuisonglianjie') as string);
				break;
			case IBusinessName.SEND_VIDEO_LINK:
				await AgentService.fetchBusinessMaterialWithPageSize({ scenId: AgentService.bizScenarioId, type: 'video', page: 1, pageSize: 99 });
				setTitle(t('tuisongshipin') as string);
				break;
			case IBusinessName.SNAP_SHOT:
				setTitle(t('select-client-for-take-shot') as string);
				break;
			case IBusinessName.FACE_COMPARE:
				setTitle(t('select-client-for-face-comparison') as string);
				break;
			case IBusinessName.CARD_COMPARE:
				setTitle(t('select-client-for-face-idcard-comparison') as string);
				break;
			case IBusinessName.SCREEN_MARK:
				setTitle(t('select-client-for-mark') as string);
				break;
			case IBusinessName.GET_GEO_LOCATION:
				setTitle(t('select-client-for-geographic-location') as string);
				break;
			case IBusinessName.SEND_SIGN:
				setTitle(t('select-client-for-signature') as string);
				break;
			case IBusinessName.SEND_SCANNER_CODE:
				setTitle(t('select-client-for-scan-code') as string);
				break;
			case IBusinessName.CUSTOMER_VIEW_MARK:
				setTitle(t('select-client-for-customer-view-mark') as string);
				break;
			case IBusinessName.FILL_FORM:
				setTitle(t('tuisongbiaodan') as string);
				break;
			case IBusinessName.SEND_PDF:
				await AgentService.fetchBusinessMaterialWithPageSize({ scenId: AgentService.bizScenarioId, type: 'document', page: 1, pageSize: 99 });
				setTitle(t('tuisongPDF') as string);
				break;
			case IBusinessName.SEND_CARD_COLLECTION:
				setTitle(t('kazhengshouji') as string);
				break;
			case IBusinessName.SHARED_WHITEDOARD:
				setTitle(t('select-client-for-share-board') as string);
				break;
			case IBusinessName.SHARED_PDF:
				await AgentService.fetchBusinessMaterialWithPageSize({ scenId: AgentService.bizScenarioId, type: 'document', page: 1, pageSize: 99 });
				setTitle(t('share-pdf') as string);
				break;
			case IBusinessName.SEND_VARIABLE_COLLECTION:
				setTitle(t('bianliangshouji') as string);
				break;
			case IBusinessName.TRANSCRIPT_OF_TESTIMONY:
				setTitle(t('zhengyanchaolu') as string);
				break;
			case IBusinessName.SEND_VIDEO_COLLECTION:
				setTitle(t('short-video-collection') as string);
				setModalWidth(456);
				break;
			case IBusinessName.TTS_BROADCAST:
				break;
			default:
				break;
		}
	};

	const getOkText = (): string => {
		let text = '';
		switch (sendCommandModalType) {
			case IBusinessName.FILL_FORM:
				text = t('invite-fill');
				break;
			case IBusinessName.SEND_CARD_COLLECTION:
				text = t('confirm-collect');
				break;
			case IBusinessName.SEND_VARIABLE_COLLECTION:
				text = t('confirm-the-collect');
				break;
			default:
				text = t('confirm');
				break;
		}
		return text;
	};

	const getCustomerData = () => {
		let customerMembers = AgentService.getCustomerMediaStream();
		console.log(customerMembers, ':customerMembers');
		let getCustomerName: customerNameProps[] = [];
		let getCustomerRole: customerRoleProps[] = [];
		getCustomerName = customerMembers.map(item => {
			return {
				name: item.userName,
				active: (sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION || sendCommandModalType === IBusinessName.CUSTOMER_VIEW_MARK) && showCustomerRoleOrName ? false : true,
				clientId: item.clientId,
				id: item.id!.toString()
			};
		});
		getCustomerRole = customerMembers.map(item => {
			return {
				name: item.customerRole || '',
				active: true
			};
		});
		getCustomerRole = getCustomerRole.reduce((all: any[], next: { [x: string]: any }) => (all.some((item: { [x: string]: any }) => item['name'] == next['name']) ? all : [...all, next]), []);
		console.log(getCustomerName, ':getCustomerName', getCustomerRole, ':getCustomerRole');
		setCustomerName(getCustomerName);
		setCustomerRole(getCustomerRole);
	};

	const selectNameOrRole = (data: any) => {
		let newCustomerName: any = [];
		if (data.clientId) {
			// 实时标注，只能单选访客
			newCustomerName = customerName.map(item => {
				const isActive =
					sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION || sendCommandModalType === IBusinessName.CUSTOMER_VIEW_MARK
						? item.name === data.name
							? true
							: false
						: item.name === data.name
						? !item.active
						: item.active;
				return {
					name: item.name,
					active: isActive,
					clientId: item.clientId
				};
			});
			setCustomerName(newCustomerName);
		} else {
			newCustomerName = customerRole.map(item => {
				return {
					name: item.name,
					active: item.name === data.name ? !item.active : item.active
				};
			});
			setCustomerRole(newCustomerName);
		}
	};

	const onChangeSendLink = (e: any) => {
		if (e) {
			console.log(e);
			setLink(e.target.value);
		}
	};

	const onChangeSendVideo = (e: any) => {
		if (e) {
			console.log(e);
			let url = e.url.replace(/^(http:\/\/)/, 'https://');
			setVideo(url);
		}
	};

	const onChangeSendPDF = (e: any) => {
		if (!e) {
			setPdfResource(initialPdfResource);
		} else {
			setPdfResource(e);
		}
	};

	const onChangeCardType = (type: string) => {
		if (type) {
			setCardType(type);
		}
	};

	const getSendData = () => {
		let data: string[] = [];
		let customerMembers = AgentService.getCustomerMediaStream();
		if (showCustomerRoleOrName) {
			if (tabTypes === 'customerNameTabs') {
				customerName.forEach(item => {
					if (item.active) {
						data.push(item.clientId);
					}
				});
			} else {
				customerRole.forEach(item => {
					if (item.active) {
						customerMembers.forEach(ele => {
							if (ele.customerRole === item.name) {
								data.push(ele.clientId);
							}
						});
					}
				});
			}
		} else {
			data.push(customerMembers[0].clientId);
		}

		return data;
	};

	const getCustomerStreamId = () => {
		let data: string[] = [];
		let customerMembers = AgentService.getCustomerMediaStream();
		if (tabTypes === 'customerNameTabs') {
			customerName.forEach(item => {
				if (item.active) {
					data.push(item.id);
				}
			});
		} else {
			customerRole.forEach(item => {
				if (item.active) {
					customerMembers.forEach(ele => {
						if (ele.customerRole === item.name) {
							data.push(ele.id!.toString());
						}
					});
				}
			});
		}
		return data;
	};

	const verification = () => {
		let data = getSendData();
		let flag = false;
		if (data.length === 0) {
			if (tabTypes === 'customerNameTabs') {
				// 只选择访客名
				const isSingleOptionNameCmd = sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION || sendCommandModalType === IBusinessName.CUSTOMER_VIEW_MARK;
				setSelectErrorMessage(isSingleOptionNameCmd ? '*' + t('select-client-for-push') : '*' + t('select-client-role-for-push'));
			} else {
				setSelectErrorMessageRole('*' + t('select-client-role-for-push'));
			}
			flag = true;
		} else {
			setSelectErrorMessage('');
			setSelectErrorMessageRole('');
		}
		if (sendCommandModalType === IBusinessName.SEND_LINK) {
			if (!link) {
				setErrorMessage(t('push-link-not-empty') as string);
				flag = true;
			} else {
				let re = new RegExp('^(https)://', 'i');
				if (re.test(link)) {
					setErrorMessage('');
				} else {
					setErrorMessage(t('push-link-begin-https') as string);
					flag = true;
				}
			}
		} else if (sendCommandModalType === IBusinessName.SEND_VIDEO_LINK) {
			if (!video) {
				setErrorMessage(t('please-select-video-file') as string);
				flag = true;
			} else {
				let re = new RegExp('^(https)://', 'i');
				if (!re.test(video)) {
					setErrorMessage(t('push-video-link-begin-https') as string);
					flag = true;
				} else {
					setErrorMessage('');
				}
			}
		} else if (sendCommandModalType === IBusinessName.FILL_FORM) {
			if (form.current) {
				form.current.validateFields();
			}

			console.log(formTemp(), 'FILL_FORM');

			if (!formTemp() || formTemp()?.length == 0) {
				setErrorMessage('*' + t('select-form-to-push'));
				flag = true;
			} else {
				flag = false;
			}
		} else if (sendCommandModalType === IBusinessName.SEND_PDF || sendCommandModalType === IBusinessName.SHARED_PDF) {
			if (pdfStatus() === UploadStatus.PROGRESS) {
				setErrorMessage('*' + t('wait-pdf-uploaded'));
				flag = true;
			} else if (!pdfResource().url) {
				setErrorMessage('*' + t('please-select-pdf-file'));
				setPdfResource(initialPdfResource);
				flag = true;
			} else {
				setErrorMessage('');
			}
		} else if (sendCommandModalType === IBusinessName.SEND_CARD_COLLECTION) {
			if (!cardType) {
				setErrorMessage('*' + t('select-collection-card'));
				flag = true;
			}
		} else if (sendCommandModalType === IBusinessName.TRANSCRIPT_OF_TESTIMONY) {
			if (!transcriptValue()) {
				setErrorMessage('*' + t('select-testimony-transcribe'));
				flag = true;
			} else {
				setErrorMessage('');
			}
		} else if (sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION) {
			if (checkedVariablesList().length === 0) {
				setErrorMessage('*' + t('select-collect-variable'));
				flag = true;
			} else {
				setErrorMessage('');
			}
		} else if (sendCommandModalType === IBusinessName.SEND_VIDEO_COLLECTION) {
			if (!videoCollectionTime()) {
				setErrorMessage('*' + t('select-collection-duration'));
				flag = true;
			} else {
				setErrorMessage('');
			}
		}
		return flag;
	};

	const getSendBusinessType = async () => {
		let data = getSendData();
		let streamData = getCustomerStreamId();
		switch (sendCommandModalType) {
			case IBusinessName.SCREEN_SHOT:
				await sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.SCREEN_SHARE:
				sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.SEND_LINK:
				sendBusiness(sendCommandModalType!, link, data);
				break;
			case IBusinessName.SEND_VIDEO_LINK:
				sendBusiness(sendCommandModalType!, video, data);
				break;
			case IBusinessName.FACE_COMPARE:
				sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.CARD_COMPARE:
				sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.SNAP_SHOT:
				await sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.GET_GEO_LOCATION:
				await sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.SEND_SIGN:
				await sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.SEND_SCANNER_CODE:
				await sendBusiness(sendCommandModalType!, '', data);
				break;
			// 实时标注
			case IBusinessName.CUSTOMER_VIEW_MARK:
				await sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.FILL_FORM:
				await sendBusiness(sendCommandModalType!, formTemp(), data);
				break;
			case IBusinessName.SEND_PDF:
				await sendBusiness(sendCommandModalType!, pdfResource(), data);
				break;
			case IBusinessName.SEND_CARD_COLLECTION:
				await sendBusiness(cardType === 'idCard' ? IBusinessName.SEND_IDCARD_COLLECTION! : IBusinessName.SEND_BANKCARD_COLLECTION!, cardType, data);
				break;
			case IBusinessName.SHARED_WHITEDOARD:
				await startWhiteBoard();
				await sendBusiness(sendCommandModalType!, '', data);
				break;
			case IBusinessName.SHARED_PDF:
				const pdfData = pdfResource();
				await startPdfWhiteBoard(pdfResource().url);
				await sendBusiness(sendCommandModalType!, pdfData, data);
				break;
			case IBusinessName.TRANSCRIPT_OF_TESTIMONY:
				const transcript = AgentService.transcriptData.find(item => item.id === transcriptValue());
				await sendBusiness(sendCommandModalType!, { content: transcript.message }, data);
				break;
			case IBusinessName.SEND_VARIABLE_COLLECTION:
				const variableData = AgentService.collectionVariable.filter(item => checkedVariablesList().includes(item.id));
				await sendBusiness(sendCommandModalType!, variableData, data);
				break;
			case IBusinessName.SEND_VIDEO_COLLECTION:
				await sendBusiness(sendCommandModalType!, { time: videoCollectionTime() }, data);
				break;
			default:
				break;
		}
		setLink('');
		setVideo('');
		setPdfResource(initialPdfResource);
	};

	const submit = () => {
		if (verification()) return;
		getSendBusinessType();
		setSelectErrorMessage('');
		setSelectErrorMessageRole('');
		setErrorMessage('');
		if (AgentService.transcriptData.length !== 0) {
			setTranscriptValue(AgentService.transcriptData[0].id);
		} else {
			setTranscriptValue('');
		}

		onOk && onOk();
	};

	const getFormTemplate = (data: any) => {
		console.log(data);
		setFormTemp(data);
	};

	const onChangeTranscriptGroups = (e: RadioChangeEvent) => {
		setTranscriptValue(e.target.value);
	};

	const onChangeVariablesList = (e: CheckboxValueType[]) => {
		setCheckedVariablesList(e);
		setCheckVariablesListAll(e.length === AgentService.collectionVariable.length);
	};

	const onCheckVariablesListAllChange = (e: CheckboxChangeEvent) => {
		setCheckedVariablesList(e.target.checked ? AgentService.collectionVariable.map(item => item.id) : []);
		setCheckVariablesListAll(e.target.checked);
	};

	const TitleContianer = styled.p`
		font-size: 13px;
		font-weight: 400;
		color: #202020;
		margin: 0;
	`;

	const getFormPreview = useMemo(() => {
		if (sendCommandModalType === IBusinessName.FILL_FORM && formTemp()?.length !== 0) {
			return <FormPreview list={formTemp()?.map(item => ({ id: item.formTemplate.id, title: item.formTemplate.fields.title, detailId: undefined })) || []} />;
		}
	}, [formTemp(), sendCommandModalType]);

	return (
		<div>
			<Modal
				width={modalWidth()}
				title={title}
				open={visible}
				destroyOnClose={true}
				className="send-command-modal"
				onCancel={() => {
					onClose && onClose();
					setErrorMessage('');
					setSelectErrorMessage('');
					setSelectErrorMessageRole('');
				}}
				onOk={submit}
				okText={getOkText()}
				cancelText={t('cancel')}
			>
				{sendCommandModalType === IBusinessName.SEND_LINK ? <SendLink onChangeSendLink={onChangeSendLink} errorMessage={errorMessage} /> : ''}
				{sendCommandModalType === IBusinessName.SEND_VIDEO_LINK ? <SendVideo onChangeSendVideo={onChangeSendVideo} errorMessage={errorMessage} /> : ''}
				{sendCommandModalType === IBusinessName.FILL_FORM ? <SendForm form={form} getFormTemplate={getFormTemplate} /> : ''}
				{sendCommandModalType === IBusinessName.SEND_PDF || sendCommandModalType === IBusinessName.SHARED_PDF ? (
					<SendPDF
						pdfStatus={pdfStatus()}
						tips={sendCommandModalType === IBusinessName.SEND_PDF ? t('upload-pdf-to-push') || '' : t('select-pdf-share') || ''}
						setPdfStatus={setPdfStatus}
						onChangeSendPDF={onChangeSendPDF}
						errorMessage={errorMessage}
						setErrorMessage={setErrorMessage}
					/>
				) : (
					''
				)}
				{/* {sendCommandModalType === IBusinessName.SEND_CARD_COLLECTION ? <SendCardCollection onChangeCardType={onChangeCardType} errorMessage={errorMessage} cardType={cardType} /> : ''} */}
				{sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION ? (
					<CollectVariable
						checkedVariablesList={checkedVariablesList()}
						onCheckVariablesListAllChange={onCheckVariablesListAllChange}
						checkVariablesListAll={checkVariablesListAll()}
						errorMessage={errorMessage}
						onChangeVariablesList={onChangeVariablesList}
					/>
				) : (
					''
				)}
				{sendCommandModalType === IBusinessName.TRANSCRIPT_OF_TESTIMONY ? (
					<Transcript errorMessage={errorMessage} transcriptValue={transcriptValue()} onChangeTranscriptGroups={onChangeTranscriptGroups} />
				) : (
					''
				)}
				{sendCommandModalType === IBusinessName.SEND_VIDEO_COLLECTION ? (
					<VideoCollection errorMessage={errorMessage} videoCollectionTime={videoCollectionTime()} setVideoCollectionTime={setVideoCollectionTime} />
				) : (
					''
				)}

				{showCustomerRoleOrName ? (
					<>
						{sendCommandModalType && hasDivider.indexOf(sendCommandModalType) !== -1 ? <Divider></Divider> : null}
						{sendCommandModalType && hasDivider.indexOf(sendCommandModalType) !== -1 ? <TitleContianer>{t('select-client-for-push')}</TitleContianer> : null}
						{sendCommandModalType === IBusinessName.SEND_VARIABLE_COLLECTION || sendCommandModalType === IBusinessName.CUSTOMER_VIEW_MARK ? null : (
							<Tabs
								tabsType={tabTypes}
								onClick={type => {
									type && setTabTypes(type);
								}}
							/>
						)}
						<SelectContent
							tabTypes={tabTypes}
							array={tabTypes === 'customerNameTabs' ? customerName : customerRole}
							onClick={selectNameOrRole}
							selectErrorMessage={selectErrorMessage}
							selectErrorMessageRole={selectErrorMessageRole}
						/>
					</>
				) : (
					''
				)}
				{getFormPreview}
			</Modal>
		</div>
	);
};

export default index;
